var com = {};

com.params = {};

com.mainColor = function(flag){
    if( flag == 'theme-custom01' ) return '#fb2d37';
    if( flag == 'theme-custom02' ) return '#ff2726';
    if( flag == 'theme-custom03' ) return '#fcc600';
    if( flag == 'theme-custom04' ) return '#ff547b';
    if( flag == 'theme-custom05' ) return '#09bb07';
    if( flag == 'theme-custom06' ) return '#65c4aa';
    if( flag == 'theme-custom07' ) return '#388cee';
    if( flag == 'theme-custom08' ) return '#c1a866';
    if( flag == 'theme-custom09' ) return '#6cbe72';
    if( flag == 'theme-custom10' ) return '#8ec31f';
    if( flag == 'theme-custom11' ) return '#e3a586';
    return '#fb2d37';
}

com.backPage = function(zfid){
    var pages = getCurrentPages();
    if( pages.length > 1 ){
        wx.navigateBack();
    }else{
        var tourl = zfid > 0 ? '/zofui_sales/pages/index/index?zfid='+options.zfid : '/zofui_sales/pages/index/index';
        wx.switchTab({
          url: tourl
        });
    }
}

// 模块链接
com.murl = function (d,querystring){
    if( querystring ) querystring.m = 'zofui_sales';
	return this.url('entry/wxapp/'+d,querystring);
}

com.setBar = function(app,that,shopid){
    var self = this;
    shopid = shopid > 0 ? shopid : 0;
    var Menu = app.globalData.shopfooter['f'+shopid];
    
    if( !that.Menu || (shopid > 0 && app.globalData.shopnav == 1) ){
        if( Menu ){
            that.setData({
                curPage : '/'+self.getUrlArgs(),
                shopid : shopid,
                Menu : Menu,
                copyright : app.globalData.copyright ? app.globalData.copyright : {},
                isIPX : app.globalData.isIPX ? true : false,
            })
        }else{       
            com.http('myinit','POST',{shopid:shopid},20,false,'','',function(res){
                if (!res.data.errno) {
                    app.globalData.shopnav = res.data.data.shopnav;
                    app.globalData.shopunav = res.data.data.shopunav;

                    app.globalData.shopfooter['f'+shopid] = res.data.data.footer;
                    app.globalData.copyright = res.data.data.copy;
                    that.setData({
                        curPage : '/'+self.getUrlArgs(),
                        shopid : shopid,
                        Menu : res.data.data.footer ? res.data.data.footer : [],
                        copyright : res.data.data.copy ? res.data.data.copy : {},
                        isIPX : app.globalData.isIPX ? true : false,
                    })
                }
            })
            
            
        }
    }
}

com.url = function (action, querystring) {
    var app = getApp();
    var url = app.siteInfo.siteroot + '?i=' + app.siteInfo.uniacid + '&t=' + app.siteInfo.multiid + '&v=' + app.siteInfo.version + '&from=wxapp&';

    if (action) {
        action = action.split('/');
        if (action[0]) {
            url += 'c=' + action[0] + '&';
        }
        if (action[1]) {
            url += 'a=' + action[1] + '&';
        }
        if (action[2]) {
            url += 'do=' + action[2] + '&';
        }
    }   
    if (querystring && typeof querystring === 'object') {
        for (let param in querystring) {
            if (param && querystring.hasOwnProperty(param) && querystring[param]) {
                url += param + '=' + querystring[param] + '&';
            }
        }
    }   
    return url;
}


com.http = function(doo,method,data,cachetime,loading,success,fail,complete){
    var app = getApp();
	var cachetime = app.siteInfo.siteroot == 'http://127.0.0.6/app/index.php' ? 0 : cachetime;

    if(doo == 'admin'){
        var loginsid = wx.getStorageSync('adminshopid');
        data.loginsid = loginsid ? loginsid : '';
    }
    data.from_scene = app.globalData.scene;
    
    app.util.request({
        url: app.com.murl(doo),
        method : method,
        cachetime: cachetime ? cachetime : 0,
        data : data,
        showLoading : loading ? true : false,
        success: function (res) {
            
            if( success && res.data && res.data.errno != 41009 ) success( res );
      	},
      	complete : function(res){
      		if( complete && res.data && res.data.errno != 41009 ) complete( res );
      	},
        fail : function(res){
            if( fail ) fail( res );
        }
    });
}


com.auth = function( cb,that ){
    var self = this;
    self.getUserInfo(
        function(res){
            if( that && ( !res.wxInfo || ( !res.wxInfo.nickname && res.wxInfo.headimgurl ) ) ){
                that.setData({
                    showuserbtn : true,
                });
            }
            if( cb ) cb(res);
        },
        function(res){
            self.toAuth(cb);
        },
    );
}

com.toAuth = function( cb ){
    var self = this;
    wx.showModal({
        title: '提示',
        content : '请允许使用您的用户信息',
        showCancel : false,
        complete : function() {
            wx.openSetting({
                success: function(resa){
                    
                    if( !resa.authSetting['scope.userInfo'] ) {
                        self.toAuth( cb );
                    }else{
                        self.auth( cb );
                    }
                }
            })
        }
    });
}

/*
* 获取用户信息 wxInfo有数据即需要更新会员昵称等
*/

com.getUserInfo = function ( cb,fb,wxInfo ) {
    var app = getApp();
    if(app.globalData.scene == 1154){
        cb();
        return false;
    }
    var login = function() {
        var userInfo = {
            'sessionid': '',
            'wxInfo': '',
            'memberInfo': '',
        };
        wx.login({
            success: function (res) {
                console.log(res)
                app.util.getWe7User(function(userInfo) {
                    if (wxInfo) {
                        app.util.upadteUser(wxInfo, function(userInfo) {
                            typeof cb == "function" && cb(userInfo);
                        })
                    } else {
                        typeof cb == "function" && cb(userInfo);
                    }
                }, res.code)
            },
            fail: function () {
                wx.showModal({
                    title: '获取信息失败',
                    content: '请允许授权以便为您提供服务',
                    success: function (res) {
                        if (res.confirm) {
                            app.util.getUserInfo();
                        }
                    }
                })
            }
        });
    };

    var userInfo = wx.getStorageSync('userInfo') || {};
    if (userInfo.sessionid) {
        if( !wxInfo ){
            typeof cb == "function" && cb(userInfo);
            return;
        }

        app.util.checkSession({
            success: function(){
                if (wxInfo) {
                    app.util.upadteUser(wxInfo, function(userInfo) {
                        typeof cb == "function" && cb(userInfo);
                    })
                } else {
                    typeof cb == "function" && cb(userInfo);
                }
            },
            fail: function(){
                userInfo.sessionid = '';
                wx.removeStorageSync('userInfo');
                login();
            }
        })
    } else {
        //调用登录接口
        login();
    }
}


com.getPage = function(that,data,cachetime,succall,comcall,fail,dataname){
    if( data.doing || data.isend ) return false;
    var dataname = dataname ? dataname : 'page';
    that.setData({
        [`${dataname}.nodataf`] : 0,
        [`${dataname}.waitf`] : 1,
    });
    that.data.doing = true;

    let isload = data.isloading ? true : false;
    this.http( data.doo ? data.doo : 'pagelist','GET',data.pdata,cachetime,isload,function(res){
        if( res.data.data.list.length > 0 ){
            data.pdata.page ++;
        }else{
            data.isend = true;
            that.setData({
                [`${dataname}.nodataf`] : 1,
            });
        }
        if( succall ) succall(res);

    },function(res){

        if( fail ) fail(res);

    },function(res){
        if( comcall ) comcall(res);
        that.setData({
            [`${dataname}.waitf`] : 0
        });
        that.data.doing = false;
    });
}


com.getSet = function(){
    var set = wx.getStorageSync('set');
    var now = new Date().getTime()/1000;
    if( typeof set == 'undefined' || set == '' || set.data.length <= 0 || set._expiretime <= now ){
        this.http('ajax','get',{op:'set'},30,false,function(res){
            if( res.data.data ){
                set = {'_expiretime':now+60,data:res.data.data};
                wx.setStorageSync('set', set);
            }else{
                set = {};
            }
        });
    }
    return set.data;
}

com.location = function( e ){
    wx.openLocation({
      latitude:  parseFloat(e.currentTarget.dataset.lat),
      longitude: parseFloat(e.currentTarget.dataset.lng),
      name : e.currentTarget.dataset.addname,
      address : e.currentTarget.dataset.address,
      scale: 13
    });
}

com.otherapp = function( e ){
          
    wx.navigateToMiniProgram({
        appId: e.currentTarget.dataset.appid,
        path: e.currentTarget.dataset.appurl,
        success : function(){
            console.log( 'tosuc' );
        },
        fail : function(m){
            var app = getApp();
            //console.log( m );
            app.util.message(m.errMsg,'','error');  
        }
    });
}

com.navigateto = function( e ){
    var url = e.currentTarget.dataset.url;
    if( url ) {
        if(url == '/zofui_sales/pages/index/index' || url == '/zofui_sales/pages/user/user' || url == '/zofui_sales/pages/ucard/ucard' || url == '/zofui_sales/pages/shop/list' || url == '/zofui_sales/pages/comment/comment'){
            wx.switchTab({
              url: url
            })
        }else{
            var pages = getCurrentPages();
            if( pages.length >= 10 ){
                wx.reLaunch({
                  url: e.currentTarget.dataset.url
                })
            }else{ 
                wx.navigateTo({
                  url: e.currentTarget.dataset.url
                })
            }
        }
    }
}

com.redirectto = function( e ){
    var url = e.currentTarget.dataset.url;
    if( url ) {
        if(url == '/zofui_sales/pages/index/index' || url == '/zofui_sales/pages/user/user' || url == '/zofui_sales/pages/ucard/ucard' || url == '/zofui_sales/pages/shop/list' || url == '/zofui_sales/pages/comment/comment'){
            wx.switchTab({
              url: url
            })
        }else{

            var pages = getCurrentPages();
            if( pages.length >= 10 ){
                wx.reLaunch({
                  url: e.currentTarget.dataset.url
                })
            }else{
                wx.redirectTo({
                  url: e.currentTarget.dataset.url
                })
            }
        }
    }
}

com.callphone = function(e){
    
    var tel = e.currentTarget.dataset.tel || e.detail.tel;
    if( tel ) {
        wx.makePhoneCall({
          phoneNumber: tel
        });
    }
}

com.toweburl = function( e,that ){
    var weburl = encodeURIComponent( e.currentTarget.dataset.weburl );
    wx.navigateTo({
      url: '/zofui_sales/pages/webview/webview?url='+weburl,
    });
}

com.showimages = function( e ){
    
    var img = [];
    if( e.currentTarget.dataset.img[0].url ){
        for (var i = 0; i < e.currentTarget.dataset.img.length; i++) {
            img.push( e.currentTarget.dataset.img[i].url );
        }
    }else{
        img = e.currentTarget.dataset.img;
    }
    wx.previewImage({
        urls: img
    });
}

// 下拉刷新
com.pullDown = function( that ){
    if( that.data.isdown ) return false;
    that.setData({
        isdown : true,
    });
    that.onLoad( that.data.options );
    that.setData({
        isdown : false,
    });
}

com.isArr = function(arr){
    return Object.prototype.toString.call(arr) === '[object Array]'; 
}

com.toast = function(title,type,comcall){
    wx.showToast({
        title: title,
        icon: type ? type : 'none',
        duration: 1800,
        mask : type == 'none' || !type ? false : true,
        complete : function(){
            if( comcall ) {
                setTimeout(function(){
                    comcall();
                },1000);
            }
        }
    });
};

com.alert = function(title,fna,fnb){
    wx.showModal({
        title: '提示',
        content: title,
        showCancel : false,
        success: function(res) {
            if (res.confirm) {
                if( fna ) fna(res);
            } else if (res.cancel) {
                if( fnb ) fnb(res);
            }
        }
    });
};

com.confirm = function(title,fna,fnb,canceltext,confirmtext){
    wx.showModal({
        title: '提示',
        content: title,
        showCancel : true,
        cancelText : canceltext ? canceltext : '取消',
        confirmText : confirmtext ? confirmtext : '确定',
        success: function(res) {
            if (res.confirm) {
                if( fna ) fna(res);
            } else if (res.cancel) {
                if( fnb ) fnb(res);
            }
        }
    });
};

com.verify = function(type,parama,paramb){
    if(type == 'number'){
        if(parama == 'int'){ // 正整数
            var R = /^[1-9]*[1-9][0-9]*$/;
        }else if(parama == 'intAndLetter'){ //数字和字母
            var R = /^[A-Za-z0-9]*$/;
        }else if(parama == 'money'){ //金额,最多2个小数
            var R = /^\d+\.?\d{0,2}$/;
        }
        return R.test(paramb);
    }else if(type == 'mobile'){ //手机
        var R = /^1[3|4|5|6|7|8|9]\d{9}$/;
        var R1 = /^0[3|4|5|6|7|8|9]\d{8}$/;
        return R.test(parama) || R1.test(parama);
        
    }else if(type == 'cn'){ //中文
        var R = /^[\u2E80-\u9FFF]+$/;
        return R.test(parama);
    }
};

// 清除搜索记录
com.clearhist = function(that,$plug){
    wx.removeStorage({key:'zofui_searchhist'+$plug});
    that.setData({
      searchhist: [],
    });
};

// 增加搜索记录
com.addhist = function(that,key,plug){
    
    if( that.data.searchhist.indexOf( key ) >= 0 ) return false;
    that.data.searchhist.unshift( key );
    // 删除多余的
    if( that.data.searchhist.length >= 10 ) {
        that.data.searchhist.splice(10,that.data.searchhist.length);
    }
    wx.setStorageSync('zofui_searchhist'+plug, that.data.searchhist);
    that.setData({
        searchhist: that.data.searchhist
    });
};

com.tosearchhist = function( that,plug ){

    var url = '/zofui_sitetemp/pages/goodlist/goodlist?for='+that.data.for;
    if( plug == 1 ) url = '/zofui_sitetemp/pages/deskorder/goodlist?for='+that.data.for;

    wx.navigateTo({
      url: url,
    })
}

com.tosearch = function( that,plug ){
    if( !that.data.for ){
        return false;
    }
    that.addhist( that.data.for,plug );
    var url = '/zofui_sitetemp/pages/goodlist/goodlist?for='+that.data.for;
    if( plug == 1 ) url = '/zofui_sitetemp/pages/deskorder/goodlist?for='+that.data.for;
    wx.navigateTo({
      url: url,
    })
}

/*获取当前页url*/
com.getUrl = function(){
    var pages = getCurrentPages();   //获取加载的页面
    var currentPage = pages[pages.length-1];    //获取当前页面的对象
    return currentPage.route;    //当前页面url
}


/*获取当前页带参数的url*/
com.getUrlArgs = function(){
    var pages = getCurrentPages()    //获取加载的页面
    var currentPage = pages[pages.length-1]    //获取当前页面的对象
    var url = currentPage.route    //当前页面url
    var options = currentPage.options    //如果要获取url中所带的参数可以查看options
    
    //拼接url的参数
    var urlWithArgs = url + '?'
    for(var key in options){
        if(key != 'zfid' && key != 'isposter' && key != 'id' && key != 'gid'){
            var value = options[key]
            urlWithArgs += key + '=' + value + '&'
        }
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length-1)
    
    return urlWithArgs
}

com.theRequest = function( url ){

    var theRequest = {};
    if (url.indexOf("?") != -1) {  
        var str = url.split("?");
        var strs = str[1].split("&");
        for(var i = 0; i < strs.length; i ++) {  
            theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);  
        }
    }
    return theRequest;
    
}

com.getLocation = function(that,fn){
    var loc = wx.getStorageSync('nlloc');
    var now = new Date().getTime();

    var self= this;
    that.setData({
        loc : loc,
    });
    if( !!loc && loc.expire && loc.expire > now ){
        fn( loc );
    }else{
        wx.getLocation({
            type: 'gcj02',
            success : function(res){
                self.locsucces(res,fn,1);
            },
            fail : function(res){
            	console.log(res)

                var isneed = wx.getStorageSync('needloc');
                if( isneed*1 <= now ){
                	wx.getSetting({
                		success (resg) {
                			if( !resg.authSetting['scope.userLocation'] ){
			                    self.confirm('请开启位置授权,以便为您提供服务',function(){
			                        wx.openSetting({
			                            complete : function(resa){
			                                if( !resa.authSetting['scope.userLocation'] ){
			                                    fn({latitude : 11,longitude : 11});
			                                }else{
			                                    self.locsucces('',fn,2);
			                                }
			                            }
			                        });
			                    },function(){
			                        fn({latitude : 11,longitude : 11});
			                    })
                                var end = new Date().getTime() + 300*1000;
                                wx.setStorageSync('needloc',end);

                			}else{
                				fn({latitude : 11,longitude : 11});
                			}
                		}
                	})
                }else{
                    fn({latitude : 11,longitude : 11});
                }
            },
        });
    }
}

com.locsucces = function(loc,fn,type){
    var now = new Date().getTime();

    if( type == 1 ){
        wx.setStorageSync('nlloc',{latitude:loc.latitude,longitude:loc.longitude,expire:now+300*1000});
        fn( loc );
    }else{
        wx.getLocation({
            success : function(res){
            	console.log(res)
                wx.setStorageSync('nlloc',{latitude:res.latitude,longitude:res.longitude,expire:now+300*1000});
                fn( res );
            },
        });
    }
}


com.notloc = function(){
    var app = getApp();
    wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.userLocation']) {
            app.com.alert('请开启位置功能为你提供最近的服务',function(){
                wx.openSetting();
            });
          }
        }
    })
};

com.uptomaster = function(tempurl,fn){
    wx.showLoading({mask:true,title:'上传中'});
    var app = getApp();
    wx.uploadFile({
        url: app.siteInfo.siteroot+'?i='+app.siteInfo.uniacid+'&j=&c=utility&a=file&do=upload&type=image&thumb=0',
        filePath: tempurl,
        name: 'file',
        success: function(res){
            var aaa = JSON.parse( res.data );
            if( fn ) fn( aaa );
        },
        complete : function(){
            wx.hideLoading();
        }
    })
};

com.copy = function(e){
    var self = this;
    var text = e.currentTarget.dataset.text;
    if( text ) {
        wx.setClipboardData({
            data : text,
            success : function(){}
        });
    }
}

com.totime = function(unixtime){  
    var myDate = new Date(parseInt(unixtime));
    var year = myDate.getFullYear();  
    var month = myDate.getMonth() + 1;  
    var day = myDate.getDate();
    var hours = myDate.getHours();
    var minutes = myDate.getMinutes();  
    return year + '-' + month + '-' + day + ' '+hours+':'+minutes; 
} 

com.sendGo = function(content,channel,pusher){  
    var app = getApp();
    var pre = pusher ? 'pusher' : 'live';
    app.globalData.goEasy.publish({
        channel: pre+channel,
        message: content
    });
} 

module.exports = com;